import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/dialog/two_result_hint_dialog.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/mixins/page_stay_time.dart';
import 'package:distribution_mall_flutter/pages/home/home.dart';
import 'package:distribution_mall_flutter/pages/merchant_authentication/state/merchant_authentication_state.dart';
import 'package:distribution_mall_flutter/router/router.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/input_decoration_utils.dart';
import 'package:distribution_mall_flutter/utils/keyboard.dart';
import 'package:distribution_mall_flutter/widgets/click_dismiss.dart';
import 'package:distribution_mall_flutter/widgets/easy_refresh.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:image_picker/image_picker.dart';

import 'application/merchant_authentication_service.dart';
import 'merchant_authentication_provider.dart';

@RoutePage()
class MerchantAuthenticationPage extends StatefulHookConsumerWidget {
  const MerchantAuthenticationPage({super.key});

  @override
  ConsumerState<MerchantAuthenticationPage> createState() =>
      _MerchantAuthenticationPageState();
}

class _MerchantAuthenticationPageState
    extends ConsumerState<MerchantAuthenticationPage>
    with PageStayTime<MerchantAuthenticationPage> {
  final easyRefreshController =
      EasyRefreshController(controlFinishRefresh: true);
  @override
  String pageStayName = RouteInfoEnum.merchantAuthentication.routeZhName;
  @override
  Map<String, Object?> pageStayMap = {};

  @override
  Widget build(BuildContext context) {
    ref.watch(merchantAuthenticationServiceProvider);
    var merchantAuthenticationState = ref.watch(merchantAuthenticationProvider);
    bool canEdit = false;

    ///没认证
    if (merchantAuthenticationState.merchantAuthLastBody == null &&
        merchantAuthenticationState.loadSuccess) {
      pageStayMap['verification_status'] = 1;
      canEdit = true;
    } else {
      ///审核状态(eq): 审查中 REVIEW, 通过 PASS, 拒绝 REJECT
      if (merchantAuthenticationState.merchantAuthLastBody?.auditState ==
          'REJECT') {
        canEdit = true;
        pageStayMap['verification_status'] = 2;
      } else {
        canEdit = false;
      }
    }

    return ClickDisMiss(
      child: Form(
        child: Builder(builder: (context) {
          return Scaffold(
            appBar: AppBar(
              title: Text(S.current.authentication),
              centerTitle: false,
              leading: CommonBtnWidget.arrowBack(),
            ),
            bottomNavigationBar: canEdit
                ? Container(
                    height: 42,
                    margin:
                        const EdgeInsets.only(left: 24, right: 24, bottom: 19),
                    child: ElevatedButton(
                      onPressed: () async {
                        KeyboardUtils.hideByContext(context);
                        bool notSelectedImage;

                        ///如果是被拒状态,如果有网络图片也可以直接上传
                        if (merchantAuthenticationState
                                .merchantAuthLastBody?.auditState ==
                            'REJECT') {
                          notSelectedImage = merchantAuthenticationState
                                  .merchantAuthLastBody?.businessPermitUrl ==
                              null;
                        } else {
                          notSelectedImage = ref.read(
                                  merchantAuthenticationSelectImageFileProvider) ==
                              null;
                        }
                        if (notSelectedImage) {
                          ref
                              .read(
                                  merchantAuthenticationSelectImageFileShowErrorProvider
                                      .notifier)
                              .setError(true);
                        }
                        if (Form.of(context).validate() && !notSelectedImage) {
                          bool? result = await showDialog(
                              context: context,
                              builder: (_) => TwoResultHintDialog(
                                  title: S.current.confirm_submission,
                                  leftText: S.current.cancel,
                                  rightText: S.current.yes));
                          if (result == true) {
                            ref
                                .read(merchantAuthenticationServiceProvider)
                                .commit(
                                    businessName: merchantAuthenticationState
                                        .businessNameController.text,
                                    certificateNo: merchantAuthenticationState
                                        .certificateNoController.text,
                                    tel: merchantAuthenticationState
                                        .phoneNumberController.text,
                                    detailed: merchantAuthenticationState
                                        .addressDetailController.text);
                          }
                        }
                      },
                      child: const Text('Submit'),
                    ),
                  )
                : null,
            body: SizedBox(
              width: double.infinity,
              child: EasyRefresh(
                controller: easyRefreshController,
                onRefresh: canEdit
                    ? null
                    : () async {
                        await ref
                            .read(merchantAuthenticationServiceProvider)
                            .queryLast();
                        easyRefreshController.finishRefresh();
                        easyRefreshController.resetFooter();
                      },
                refreshOnStartHeader: easyFirstRefreshBuilderHeader,
                refreshOnStart: true,
                child: CustomScrollView(
                  slivers: [
                    SliverPadding(
                      padding: const EdgeInsets.only(
                          left: 24, right: 24, top: 22, bottom: 25),
                      sliver: SliverToBoxAdapter(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            buildTopCard(merchantAuthenticationState),
                            Text(S.current.business_name,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 24),
                              child: IgnorePointer(
                                ignoring: !canEdit,
                                child: TextFormField(
                                  controller: merchantAuthenticationState
                                      .businessNameController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: formInputDecoration.copyWith(
                                    hintText: S.current.business_name,
                                  ),
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(200)
                                  ],
                                  autovalidateMode:
                                      AutovalidateMode.onUserInteraction,
                                  validator: (str) {
                                    if (str?.isNotEmpty == true) {
                                      return null;
                                    }
                                    return S.current.please_enter_business_name;
                                  },
                                ),
                              ),
                            ),
                            Text(S.current.authentication_phone_number,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 24),
                              child: IgnorePointer(
                                ignoring: !canEdit,
                                child: TextFormField(
                                  controller: merchantAuthenticationState
                                      .phoneNumberController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: formInputDecoration.copyWith(
                                    hintText:
                                        S.current.authentication_phone_number,
                                  ),
                                  keyboardType: TextInputType.phone,
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(11),
                                    FilteringTextInputFormatter.allow(
                                        RegExp(r'[0-9]'))
                                  ],
                                  autovalidateMode:
                                      AutovalidateMode.onUserInteraction,
                                  validator: (str) {
                                    if (str?.isNotEmpty == true) {
                                      return null;
                                    }
                                    return S
                                        .current.please_enter_a_phone_number;
                                  },
                                ),
                              ),
                            ),
                            Text(S.current.business_permit_address,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 24),
                              child: IgnorePointer(
                                ignoring: !canEdit,
                                child: TextFormField(
                                  controller: merchantAuthenticationState
                                      .addressController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: formInputDecoration.copyWith(
                                      hintText: S
                                          .current.business_permit_address_hint,
                                      suffixIcon: canEdit ? Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Image.asset(
                                            Assets
                                                .assets_icons_grey_arrow_right_png,
                                            height: 16,
                                          )
                                        ],
                                      ):null),
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(200)
                                  ],
                                  onTap: () {
                                    ref
                                        .read(
                                            merchantAuthenticationServiceProvider)
                                        .selectAddress(context);
                                  },
                                  readOnly: true,
                                  autovalidateMode:
                                      AutovalidateMode.onUserInteraction,
                                  validator: (str) {
                                    if (str?.isNotEmpty == true) {
                                      return null;
                                    }
                                    return S.current.address_please_building;
                                  },
                                ),
                              ),
                            ),
                            Text(S.current.business_permit_detaled_address,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 24),
                              child: IgnorePointer(
                                ignoring: !canEdit,
                                child: TextFormField(
                                  controller: merchantAuthenticationState
                                      .addressDetailController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: formInputDecoration.copyWith(
                                    hintText: S.current
                                        .business_permit_detaled_address_hint,
                                  ),
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(200)
                                  ],
                                  autovalidateMode:
                                      AutovalidateMode.onUserInteraction,
                                  validator: (str) {
                                    if (str?.isNotEmpty == true) {
                                      return null;
                                    }
                                    return S.current.address_please_detailInfo;
                                  },
                                ),
                              ),
                            ),
                            Text(S.current.certificate_no,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 24),
                              child: IgnorePointer(
                                ignoring: !canEdit,
                                child: TextFormField(
                                  controller: merchantAuthenticationState
                                      .certificateNoController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: formInputDecoration.copyWith(
                                    hintText: S.current.certificate_no,
                                  ),
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(200)
                                  ],
                                  autovalidateMode:
                                      AutovalidateMode.onUserInteraction,
                                ),
                              ),
                            ),
                            Text(S.current.business_permit,
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600)),
                            Container(
                              margin: const EdgeInsets.only(top: 16, bottom: 8),
                              width: 164,
                              height: 164,
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      if (canEdit) {
                                        ref
                                            .read(
                                                merchantAuthenticationServiceProvider)
                                            .selectPic();
                                      }
                                    },
                                    child: Consumer(builder: (context, ref, _) {
                                      String? businessPermitUrl =
                                          merchantAuthenticationState
                                              .merchantAuthLastBody
                                              ?.businessPermitUrl;
                                      XFile? image = ref.watch(
                                          merchantAuthenticationSelectImageFileProvider);
                                      if (image != null) {
                                        if (kIsWeb) {
                                          return Image.network(
                                            image.path,
                                            width: 164,
                                            height: 164,
                                            fit: BoxFit.cover,
                                          );
                                        } else {
                                          return Image.file(
                                            File(image.path),
                                            width: 164,
                                            height: 164,
                                            fit: BoxFit.cover,
                                          );
                                        }
                                      } else if (businessPermitUrl != null) {
                                        return ExtendedImage.network(
                                          businessPermitUrl,
                                          width: 164,
                                          height: 164,
                                          fit: BoxFit.cover,
                                        );
                                      } else {
                                        return Container(
                                          padding: const EdgeInsets.all(57),
                                          decoration: BoxDecoration(
                                            color: const Color(0xFFF4F4F4),
                                            borderRadius:
                                                BorderRadius.circular(8),
                                          ),
                                          child: Image.asset(
                                            Assets.assets_icons_camera_png,
                                            width: 50,
                                          ),
                                        );
                                      }
                                    }),
                                  ),
                                  if (canEdit &&
                                      (ref.watch(merchantAuthenticationSelectImageFileProvider) !=
                                              null ||
                                          merchantAuthenticationState
                                                  .merchantAuthLastBody
                                                  ?.businessPermitUrl !=
                                              null))
                                    IgnorePointer(
                                      child: Image.asset(
                                        Assets.assets_icons_re_upload_png,
                                        width: 87,
                                      ),
                                    )
                                ],
                              ),
                            ),
                            Consumer(builder: (context, ref, _) {
                              var isError = ref.watch(
                                  merchantAuthenticationSelectImageFileShowErrorProvider);

                              return isError
                                  ? Container(
                                      margin: const EdgeInsets.only(left: 5),
                                      child: Text(
                                          S.current
                                              .please_upload_the_business_permi,
                                          style: Theme.of(context)
                                              .inputDecorationTheme
                                              .errorStyle))
                                  : Container();
                            }),
                            if (merchantAuthenticationState
                                    .merchantAuthLastBody?.auditState ==
                                'REVIEW')
                              Text(
                                S.current.estimated_to_complete_review_days,
                                style: const TextStyle(
                                    fontSize: 11, color: Color(0xFF868D96)),
                              ),
                            const SizedBox(
                              height: 50,
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  Container buildTopCard(
      MerchantAuthenticationState merchantAuthenticationState) {
    if (merchantAuthenticationState.loadSuccess) {
      ///没认证
      if (merchantAuthenticationState.merchantAuthLastBody == null) {
        return Container(
          decoration: BoxDecoration(
            color: const Color(0x24B6D4FA),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          margin: const EdgeInsets.only(bottom: 21),
          child: Text(S.current.one_time_authentication,
              style: const TextStyle(fontSize: 14, color: Color(0xFF5E5E5E))),
        );
      } else if (merchantAuthenticationState.merchantAuthLastBody?.auditState ==
          'REVIEW') {
        return Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0x24F1A156),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          margin: const EdgeInsets.only(bottom: 21),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(S.current.review,
                  style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFFFF7B00),
                      fontWeight: FontWeight.w600)),
              Text(S.current.be_reviewed_completed_within_days,
                  style:
                      const TextStyle(fontSize: 12, color: Color(0xFFFF7B00))),
            ],
          ),
        );
      } else if (merchantAuthenticationState.merchantAuthLastBody?.auditState ==
          'PASS') {
        return Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0x247FE976),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          margin: const EdgeInsets.only(bottom: 21),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(S.current.pass,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xFF31692E),
                      fontWeight: FontWeight.w600)),
              Text(S.current.congratulations_becoming_certified_user,
                  style:
                      const TextStyle(fontSize: 12, color: Color(0xFF31692E))),
            ],
          ),
        );
      } else if (merchantAuthenticationState.merchantAuthLastBody?.auditState ==
          'REJECT') {
        return Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0x24F47272),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          margin: const EdgeInsets.only(bottom: 21),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(S.current.reject,
                  style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFFE0170B),
                      fontWeight: FontWeight.w600)),
              Text(
                  merchantAuthenticationState
                          .merchantAuthLastBody?.rejectReason ??
                      '',
                  style:
                      const TextStyle(fontSize: 12, color: Color(0xFFE0170B))),
            ],
          ),
        );
      } else {
        return Container();
      }
    } else {
      return Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: const Color(0x24B6D4FA),
          borderRadius: BorderRadius.circular(8),
        ),
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
        margin: const EdgeInsets.only(bottom: 21),
        child: const Text('',
            style: TextStyle(fontSize: 14, color: Color(0xFF5E5E5E))),
      );
    }
  }
}
